<?php

namespace app\api\controller\pub;

use app\api\controller\Base;
use app\common\model\pub\Telbind;
use think\facade\Request;
use app\api\controller\Pub;

class Yunke extends Base
{
    /**
     * 云客 - 电话管理系统
     * 各位同学关于渠道后面我们提供这份接口文档https://open.smarttrust.com.cn/xdapi/doc/openChannel.html
     * 前置：创建数据库：表名[xxx_tel_bind],包含[phone]字段
     * 1、查询绑定[checkBind]：如果data为空证明已绑定，跳到第4步，
     * 2、获取验证码[imgCode]
     * 3、绑定手机号为坐席[bindPhone]
     * 4、请求回拨[dial]
     */
    private $app_key = '';
    private $partnerId = '';
    private $company = '';


    public function initialize()
    {
        // parent::initialize();
        if(!get_config_value('yunke_switch')){
            return serr('电话管理系统功能暂未开放');
        }
        $this->app_key = get_config_value('yunke_app_key');
        $this->partnerId = get_config_value('yunke_partnerId');
        $this->company = get_config_value('yunke_company');
    }

    /**
     * 获取聊天内容
     * time 时间戳以后得的内容13位
     * @return [type] [description]
     *  ["mine"] =&gt; bool(false)
        ["talker"] =&gt; string(19) "wxid_n8jeyxhnp8n522"//客户id
        ["type"] =&gt; int(1)
        ["userId"] =&gt; string(32) "F21A59F9BBCC472ABB244C99FFC7A638"
        ["roomid"] =&gt; string(0) ""
        ["msgSvrId"] =&gt; string(19) "4875741272097850527"
        ["wechatId"] =&gt; string(19) "wxid_3t6uz1igajqf12"//业务id
        ["text"] =&gt; string(72) "我通过了你的朋友验证请求，现在我们可以开始聊天了"
        ["time"] =&gt; string(13) "1740643387444"
        ["isDel"] =&gt; string(1) "0"
        ["hasHead"] =&gt; bool(true)
        ["oriTalker"] =&gt; string(19) "wxid_n8jeyxhnp8n522"
        ["timestamp"] =&gt; int(1740639751000)
     */
    public function getallRecords($time = ''){
        if(empty($time)){
            $timestamp = 1735747200000;
        }else{
            $timestamp = $time;
        }
        $reqdata = [
            'timestamp' => $timestamp,
        ];
        $req = $this->request('/open/wechat/allRecords',$reqdata);        
        if ($req['message'] !== 'success') {
            return serr($req['message']);
        }
        return sok($req['data']);
    }

    /**
     * 获取所有员工客户的微信id对应关系
     * @param  string $time [description]
     * @return [type]       [description]
     *  ["wechatId"] => string(19) "wxid_3t6uz1igajqf12"
        ["account"] => string(32) "F21A59F9BBCC472ABB244C99FFC7A638"
        ["nickname"] => string(42) "越华鹏诚危废一体机-李13678828195"
        ["phone"] => string(11) "13678827638"
        ["userPhone"] => string(11) "13678828195"
        ["headUrl"] => string(170) "https://wx.qlogo.cn/mmhead/ver_1/I2ic7icRkPRfIsPDkzIDyDDVicXULBSOuyBKoXM3pKFuyJjCxl6kLcoPGqNibFI2GicBIJOhTCPRlcFsIacwVQoPY7PIEqaf7NrvRHJKAgjPKMKRC01O2W7vQ31bxLia6ic677x/0"
        ["updateTime"] => string(19) "2025-03-02 15:08:17"
     */
    public function getcompanyAccounts(){
        $reqdata = [
            'pageSize'  => 3000
        ];
        $req = $this->request('/open/wechat/companyAccounts',$reqdata);
        if ($req['success'] !== true) {
            return serr($req['message']);
        }
        return sok($req['data']);
    }


    /**
     * 根据客户id信息获取对应信息表
     * @param  string $time [description]
     * @return [type]       [description]
     *["id"] => string(19) "wxid_s1oyjxrgv2oe22"
      ["alias"] => string(6) "BR6008"
      ["name"] => string(6) "挺好"
      ["remark"] => string(28) "赵闯大连圣菲石油3.11"
      ["type"] => int(1)
      ["fromType"] => string(1) "9"
      ["phone"] => string(0) ""
      ["description"] => string(21) "我干了、你随意"
      ["gender"] => int(1)
      ["region"] => string(13) "辽宁 大连"
      ["createTime"] => string(19) "2025-01-03 14:58:27"
      ["salesWechatId"] => string(19) "wxid_9mhp1ao4ca0a22" 销售微信id
      ["delete"] => int(0)
      ["updateTime"] => string(19) "2025-01-03 14:58:27"
     */
    public function getallFriends($starTime = '',$endTime=''){
        $reqdata = [
            'type'      => 1,//1为好友 2为群
        ];
        if(empty($starTime)){
            $timestamp = 1420041600000;
            $reqdata['timestamp'] = $timestamp;
        }else{
            $reqdata['updateTimeStart'] = $starTime;
            if(empty($endTime)){
                $endTime = date('Y-m-d H:i:s',strtotime($starTime)+3600*24*6);
            }
            $reqdata['updateTimeEnd'] = $endTime;
        }
        $req = $this->request('/open/wechat/getAllFriends',$reqdata);
        if ($req['success'] !== true) {
            return serr($req['message']);
        }
        return sok($req['data']);
    }


    /**
     * 获取通话记录,及其录音情况
     * @param  [type] $beginTime [description]
     * @param  [type] $endTime   [description]
     * @param  string $userPhone [用户的手机]
     * @param  string $phone     [description]
     * @return [type]            [description]
     * userId   string  非必须     用户id    
     * userPhone   string  非必须     用户手机号   
     * customerId  string  非必须     客户Id    
     * phone   string  非必须     客户手机号   
     * page    number  非必须     页码，默认1  mock: 1
     * size    number  非必须     每页条数，默认20，最大不超过1000 mock: 20
     * beginTime   string  必须      通话时间的起始时间(yyyy-MM-dd HH:mm:ss)  
     * endTime string  必须      通话时间的截止时间(yyyy-MM-dd HH:mm:ss)  
     */
    public function call_records($beginTime='',$endTime='',$userPhone='',$phone='')
    {
        $beginTime = empty($beginTime)?date('Y-m-d 00:00:00',time()):$beginTime;
        $endTime = empty($endTime)?date('Y-m-d 24:00:00',time()):$endTime;
        $reqdata = [
            'beginTime' => $beginTime,
            'endTime' => $endTime,
        ];
        if(!empty($userPhone)){
            $reqdata['userPhone'] = $userPhone;
        }
        if(!empty($phone)){
            $reqdata['phone'] = $phone;
        }        
        $req = $this->request('/open/call/records',$reqdata);
        if ($req['message'] !== 'success') {
            return serr($req['message']);
        }
        return sok($req['data']);
    }

    /**
     * 根据手机号获取用户数据
     * @return [type] [description]
     */
    public function getuser_by_phone($phone,$return = false){
        $reqdata = [
            'phone' => $phone,
        ];
        $req = $this->request('/open/user/getUserByPhone',$reqdata);
        if ($req['message'] !== 'success') {
            return serr($req['message']);
        }
        if(!$return){
            return sok($req['data']);
        }
        return myok($req['data']);
    }

    /**
     * 微信语⾳文件转码(新版)
     * @return [type] [description]
     */
    public function getwechatAmrTrans(){
        $key = input('key');
        $reqdata = "http://yunke-pcfile.oss-cn-beijing.aliyuncs.com/wechat-voice/msg_".$key.".amr";
        $req = $this->request('/open/trans/wechatAmrTrans?ossUrl='.$reqdata);
        if ($req['success'] !== true) {
            return serr($req['message']);
        }
        return myok($req['data']);
    }


 

    public function request($path, $data = [])
    {
        $url = 'https://crm2.yunkecn.com' . $path;
        $curl = curl_init();
        $timestamp = time()*1000;
        $header = [
            'partnerId: '.$this->partnerId,
            'company: ' .$this->company,
            'timestamp: '.$timestamp,
            'sign: '.strtoupper(md5($this->app_key.$this->company.$this->partnerId.$timestamp)),
            ];
        curl_setopt($curl, CURLOPT_URL, $url);
        if ($data) {
            $jsonData = json_encode($data);
            // 设置请求头，包括 Content-Type
            $header[] = 'Content-Type: application/json';
            $header[] = 'Content-Length: ' . strlen($jsonData);
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $jsonData);
        }
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($curl);
        $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);
        if (!$response || $code != 200) {
            //错误强制返回
            return moerr('客户管理模块通讯失败，请联系管理员');
        }
        return json_decode($response, true);
    }
}